//
//  CloudViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/19.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import JXSegmentedView
/// 就诊室-云门诊
class CloudViewController: BaseViewController {
    
    private var viewModel: CloudOrderViewModel? {
        didSet {
            guard let vm = viewModel,
            let tableView = tableview else { return }
            
            tableView.isHidden = vm.showEmptyView
            emptyView.isHidden = !vm.showEmptyView
            
            emptyView.refreshClosure = { [weak self] in
                self?.tableview.isHidden = false
                self?.emptyView.isHidden = true
                self?.tableview.mj_header?.beginRefreshing()
            }
            
            tableView.reloadData()
        }
    }
    private var page = 1
    
    var loadComplete: ((Int) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        emptyView.configure(with: UIImage(named: "empty_order"),title: "您暂时还没有云门诊哦~")
        setupRefresh()
    }
    
    @IBOutlet private weak var topHeader: CloudTopHeader! {
        didSet {
            let tap = UITapGestureRecognizer(target: self, action: #selector(reservationDoctor))
            topHeader.addGestureRecognizer(tap)
        }
    }
    
    @IBOutlet private weak var bottomHeader: CloudBottomHeader!
    
    @IBOutlet private weak var tableview: UITableView! {
        didSet {
            tableview.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0)
            tableview.rowHeight = 150
            tableview.estimatedRowHeight = UITableView.automaticDimension
            tableview.backgroundColor = .background
            tableview.tableFooterView = UIView()
            tableview.register(CloudViewCell.nibForCell(),
                               forCellReuseIdentifier: CloudViewCell.reuseIdentifier())
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 数据处理
extension CloudViewController {
    private func setupRefresh() {
        guard let tableView = tableview else { return }
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
    }
    
    private func endRefresh() {
        guard let tableView = tableview else { return }
        tableView.mj_header?.endRefreshing()
    }
    
    @objc private func loadData() {
        handleData()
    }
    
    public func handleData() {
        MyOrderViewModel.getMyCloudOrder(userId: UserDefaults.userId, status: 6, success: { models in
            self.endRefresh()
            self.viewModel = CloudOrderViewModel(models: models)
            self.loadComplete?(models.count)
        }) { errorMsg in
            self.endRefresh()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc private func loginSuccess() {
        tableview.mj_header?.beginRefreshing()
    }
}

// MARK: - DataSource && Delegate
extension CloudViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CloudViewCell.reuseIdentifier(), for: indexPath) as! CloudViewCell
        if let vm = viewModel?.viewModel(of: indexPath) {
            cell.configure(with: vm)
        }
        cell.delegate = self
        return cell
    }
}

extension CloudViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(of: indexPath) else { return }
        let chatVc = ChatViewController(with: vm.diagnoseId, outpatientStatus: vm.status, readyFlag: vm.readyFlag)
        navigationController?.pushViewController(chatVc, animated: true)
    }
}

extension CloudViewController: CloudViewCellDelegate {
    func cloudViewCell(didTappedReport cell: CloudViewCell) {
        guard let indexPath = tableview.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        
        // isReady 0-未到场 1-到场
        CloudOrderViewModel.changeCloudStatus(userId: UserDefaults.userId,
                                              diagnoseId: vm.diagnoseId,
                                              isReady: 1) { (errorMsg, code) in
            switch code {
            case .success:
                self.loadData()
            case .failure:
                cell.reset()
                HUDTool.showError(message: errorMsg)
            }
        }
    }
    
    func cloundViewCell(didRefoundOrder cell: CloudViewCell) {
        guard let indexPath = tableview.indexPath(for: cell),
            let vm = viewModel?.viewModel(of: indexPath) else { return }
        
        HUDTool.showActivity()
        MyOrderViewModel.orderRefound(orderNumber: vm.orderNumber) { (success, errorMsg) in
            HUDTool.hideActivity()
            if !success {
                HUDTool.showError(message: errorMsg)
            } else {
                self.tableview.mj_header?.beginRefreshing()
            }
        }
    }
}

// MARK: - Action
extension CloudViewController {
    @objc private func reservationDoctor() {
        let departmentVc = CloudDepartmentController()
        navigationController?.pushViewController(departmentVc, animated: true)
    }
}

extension CloudViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
